package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.Coupon;
import cn.caskm.souvenirshopsystem.domain.query.CouponQuery;
import cn.caskm.souvenirshopsystem.domain.vo.CouponVO;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.CouponMapper;
import cn.caskm.souvenirshopsystem.service.CouponService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Override
    public Result<PageDTO<CouponVO>> page(CouponQuery query) {
        // 获取参数
        Long pageNum = query.getPageNum();
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        Long pageSize = query.getPageSize();
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询数据
        Page<Coupon> page = lambdaQuery()
                .like(StrUtil.isNotBlank(query.getCouponName()), Coupon::getCouponName, query.getCouponName())
                .eq(StrUtil.isNotBlank(query.getCouponType()), Coupon::getCouponType, query.getCouponType())
                .eq(StrUtil.isNotBlank(query.getStatus()), Coupon::getStatus, query.getStatus())
                .orderByDesc(Coupon::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<Coupon> coupons = page.getRecords();
        if (CollUtil.isEmpty(coupons)) {
            return Result.success(PageDTO.empty());
        }

        // 组装VO
        List<CouponVO> result = new ArrayList<>(coupons.size());
        for (Coupon coupon : coupons) {
            CouponVO vo = BeanUtil.copyProperties(coupon, CouponVO.class);
            result.add(vo);
        }

        return Result.success(PageDTO.of(result, page.getPages(), page.getTotal()));
    }

    @Override
    public Result<List<CouponVO>> getAvailableCoupons() {
        LocalDateTime now = LocalDateTime.now();
        List<Coupon> coupons = lambdaQuery()
                .eq(Coupon::getStatus, "1") // 发布中
                .le(Coupon::getStartTime, now)
                .ge(Coupon::getEndTime, now)
                .gt(Coupon::getRemainCount, 0) // 有剩余数量
                .orderByDesc(Coupon::getCreateTime)
                .list();

        if (CollUtil.isEmpty(coupons)) {
            return Result.success(new ArrayList<>());
        }

        // 组装VO
        List<CouponVO> result = new ArrayList<>(coupons.size());
        for (Coupon coupon : coupons) {
            CouponVO vo = BeanUtil.copyProperties(coupon, CouponVO.class);
            result.add(vo);
        }

        return Result.success(result);
    }

    @Override
    public Result<Void> createCoupon(Coupon coupon) {
        coupon.setCreateTime(LocalDateTime.now());
        coupon.setUpdateTime(LocalDateTime.now());
        coupon.setUsedCount(0);
        coupon.setRemainCount(coupon.getTotalCount());
        coupon.setStatus("0"); // 默认未发布

        save(coupon);
        return Result.success();
    }

    @Override
    public Result<Void> updateCoupon(Coupon coupon) {
        if (coupon.getCouponId() == null) {
            throw new BizException("优惠券ID不能为空");
        }

        Coupon existing = getById(coupon.getCouponId());
        if (existing == null) {
            throw new BizException("优惠券不存在");
        }

        coupon.setUpdateTime(LocalDateTime.now());
        updateById(coupon);
        return Result.success();
    }

    @Override
    public Result<Void> deleteCoupon(Integer couponId) {
        Coupon coupon = getById(couponId);
        if (coupon == null) {
            throw new BizException("优惠券不存在");
        }

        // 只能删除未发布的优惠券
        if (!"0".equals(coupon.getStatus())) {
            throw new BizException("只能删除未发布的优惠券");
        }

        removeById(couponId);
        return Result.success();
    }

    @Override
    public Result<Void> updateStatus(Integer couponId, String status) {
        Coupon coupon = getById(couponId);
        if (coupon == null) {
            throw new BizException("优惠券不存在");
        }

        coupon.setStatus(status);
        coupon.setUpdateTime(LocalDateTime.now());
        updateById(coupon);
        return Result.success();
    }
}
